package com.xiaoxi.xirpc.fault.retry;

import com.github.rholder.retry.*;
import com.xiaoxi.xirpc.model.RpcResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 *  固定时间间隔 重试策略
 */
@Slf4j
public class FixedIntervalRetryStrategy implements RetryStrategy{

    /**
     *  重试条件：当发生Exception异常时触发重试
     *  重试等待策略：每隔 3s 重试一次
     *  重试停止策略：重试失败 3次 后停止重试
     *  重试工作：监听重试并打印重试次数
     * @param callable
     * @return
     * @throws Exception
     */
    @Override
    public RpcResponse doRetry(Callable<RpcResponse> callable) throws Exception {
        Retryer<RpcResponse> retryer = RetryerBuilder.<RpcResponse>newBuilder()
                .retryIfExceptionOfType(Exception.class)
                .withWaitStrategy(WaitStrategies.fixedWait(3L, TimeUnit.SECONDS))
                .withStopStrategy(StopStrategies.stopAfterAttempt(3))
                .withRetryListener(new RetryListener() {
                    @Override
                    public <V> void onRetry(Attempt<V> attempt) {
                        log.info("重试次数={}", attempt.getAttemptNumber());
                    }
                }).build();
        return retryer.call(callable);
    }
}
